package hust.cs.javacourse.search.index.impl;

import hust.cs.javacourse.search.index.AbstractDocument;
import hust.cs.javacourse.search.index.AbstractDocumentBuilder;
import hust.cs.javacourse.search.index.AbstractTermTuple;
import hust.cs.javacourse.search.parse.AbstractTermTupleFilter;
import hust.cs.javacourse.search.parse.AbstractTermTupleStream;
import hust.cs.javacourse.search.parse.impl.LengthTermTupleFilter;
import hust.cs.javacourse.search.parse.impl.PatternTermTupleFilter;
import hust.cs.javacourse.search.parse.impl.StopWordTermTupleFilter;
import hust.cs.javacourse.search.parse.impl.TermTupleScanner;

import java.io.*;

public class DocumentBuilder extends AbstractDocumentBuilder {
    public DocumentBuilder () {
        super();
    }

    /**
     * 创建三元组流Document对象
     * @param docId             : 文档id
     * @param docPath           : 文档绝对路径
     * @param termTupleStream   : 文档对应的TermTupleStream
     * @return
     */
    @Override
    public AbstractDocument build(int docId, String docPath, AbstractTermTupleStream termTupleStream) {
        //List<AbstractTermTuple> tuples = new ArrayList<AbstractTermTuple>();
        AbstractDocument document = new Document(docId, docPath);   //初始化Document对象
        AbstractTermTuple tuple = termTupleStream.next();           //获取一个三元组流
        //只要tuple不为空，循环添加tuple到Document对象中
        while(tuple != null) {
            document.addTuple(tuple);
            tuple = termTupleStream.next();
        }
        return document;
    }

    /**
     * 根据文件对象创建Document对象
     * @param docId     : 文档id
     * @param docPath   : 文档绝对路径
     * @param file      : 文档对应File对象
     * @return
     */
    public AbstractDocument build(int docId, String docPath, File file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader( new FileInputStream(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        AbstractTermTupleStream scanner = new TermTupleScanner(reader);
        AbstractTermTupleFilter StopWordFilter = new StopWordTermTupleFilter(scanner);
        //System.out.println(StopWordFilter.list);
        AbstractTermTupleFilter LengthFilter = new LengthTermTupleFilter(StopWordFilter);
        //System.out.println(LengthFilter.list);
        AbstractTermTupleFilter PatternFilter = new PatternTermTupleFilter(LengthFilter);
        //System.out.println(PatternFilter.list);
        return build(docId, docPath, PatternFilter);
    }
}
